﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Example06.aspx.cs" Inherits="Chapter37.Example06" %>

<!DOCTYPE html>

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>代码清单 37-6 使用 DataTransfer 对象过滤数据</title>
    <meta name="author" content="Adam Freeman" />
    <meta name="description" content="A simple example" />
    <link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
    <style>
        #src > * {
            float: left;
        }

        #target, #src > img {
            border: thin solid black;
            padding: 2px;
            margin: 4px;
        }

        #target {
            height: 81px;
            width: 81px;
            text-align: center;
            display: table;
        }

            #target > p {
                display: table-cell;
                vertical-align: middle;
            }

            #target > img {
                margin: 1px;
            }

        img.dragged {
            background-color: lightgrey;
        }
    </style>
</head>
<body>
    <div id="src">
        <img draggable="true" id="bananas" src="images/bananas.jpg" alt="bananas" />
        <img draggable="true" id="apples" src="images/apples.jpg" alt="apples" />
        <img draggable="true" id="cherries" src="images/cherries.jpg" alt="cherries" />
        <div id="target">
            <p id="msg">Drop Here</p>
        </div>
    </div>
    <script>
        var src = document.getElementById('src');
        var target = document.getElementById('target');
        var msg = document.getElementById('msg');

        src.ondragstart = function (e) {
            e.dataTransfer.setData('Text', e.target.id);
            e.target.classList.add('dragged');
        }

        src.ondragend = function (e) {
            var elems = document.querySelectorAll('.dragged');
            for (var i = 0; i < elems.length; i++) {
                elems[i].classList.remove('dragged');
            }
        }

        src.ondrag = function (e) {
            msg.innerHTML = e.target.id;
        }

        target.ondragenter = handleDrag;
        target.ondragover = handleDrag;
        target.ondrop = handleDrop;

        function handleDrag(e) {
            if (e.dataTransfer.getData('Text') == 'banana') {
                e.preventDefault();
            }
        }

        function handleDrop(e) {
            var droggedId = e.dataTransfer.getData('Text');
            var newElem = document.getElementById(droggedId).cloneNode(false);
            target.innerHTML = '';
            target.appendChild(newElem);
            e.preventDefault();
        }
    </script>
</body>
</html>
